package com.hibase.core.api.service.api.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hibase.core.api.entity.account.MsdApiAccount;
import com.hibase.core.api.service.account.MsdApiAccountService;
import com.hibase.core.api.service.api.HibaseApiService;
import com.hibase.common.exception.HibaseAssert;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author chenfeng
 * @version 1.0
 * @date 2021/9/30 9:49
 * @des https://gitee.com/cheershi
 */
@Service
@Slf4j
public class HibaseApiServiceImpl implements HibaseApiService {

    @Autowired
    private MsdApiAccountService apiAccountService;

    @Override
    public Map<String, Object> getToken(String auth, String requestJson) {
        // step 01 初始化
        String decodeStr = Base64.decodeStr(auth);
        String randomString = RandomUtil.randomNumbers(2);
        Long timestamp = DateUtil.date().getTime()/1000;
        // step 02 检查
        String[] splitStr = StrUtil.split(decodeStr, StrUtil.COLON);
        HibaseAssert.isTrue(ArrayUtil.isNotEmpty(splitStr) &&
                splitStr.length == 2,
                "Authorization error");
        MsdApiAccount account = apiAccountService.getOne(Wrappers.<MsdApiAccount>lambdaQuery()
                .eq(MsdApiAccount::getAppid, splitStr[0])
                .eq(MsdApiAccount::getAppsecret, splitStr[1])
        );
        HibaseAssert.notNull(account,"Authorization error");
        // step 03 执行
        String sign = DigestUtils.sha1Hex(StrUtil.concat(true,
                account.getAppid(),
                account.getAppsecret(),
                timestamp.toString(),
                randomString,
                requestJson));
        Map<String,Object> result = new HashMap<>();
        result.put("timestamp",timestamp.toString());
        result.put("nonce",randomString);
        result.put("sign",sign);
        result.put("expire_time","180");
        return result;
    }
}
